import { asyncRoutes } from "@/router/routes/asyncRoutes";
import { menuDataToRouter } from "@/router/utils/menuToRouter";
import { AppRouteRecord } from "@/types/router";
import request from "@/utils/request";
import { useCommon } from "@/composables/useCommon";
import RouteConverter, { type BackendRouteData } from "@/utils/routeConverter";

interface MenuResponse {
  menuList: AppRouteRecord[];
}

export const menuService = {
  async getMenuList(delay = 300): Promise<MenuResponse> {
    try {
      const { isFrontendMode } = useCommon();

      if (isFrontendMode.value) {
        // 前端模式：使用静态路由数据
        console.log("[menuService] 使用前端静态路由模式");
        const menuData = asyncRoutes;
        const menuList = menuData.map((route) => menuDataToRouter(route));

        // 模拟接口延迟
        await new Promise((resolve) => setTimeout(resolve, delay));
        return { menuList };
      } else {
        // 后端模式：使用RouteConverter进行智能转换
        console.log(
          "[menuService] 使用后端动态路由模式，调用getRouters接口...",
        );

        const responseData = await request({
          url: "/getRouters",
          method: "get"
        });

        console.log("[menuService] 后端返回原始数据:", responseData);

        // 🔧 正确提取路由数组：兼容新旧客户端响应格式
        // 新客户端返回 {rows, data, total, ...}，旧客户端直接返回数组
        const routeArray = (responseData as any).rows 
                        || (responseData as any).data 
                        || responseData;

        console.log("[menuService] 提取的路由数组:", routeArray);

        // 使用RouteConverter进行数据结构转换
        const menuList = RouteConverter.convertToFrontend(routeArray as BackendRouteData[]);

        console.log("[menuService] 转换后的菜单数据:", menuList);

        // 获取转换统计信息
        const statistics = RouteConverter.getStatistics(menuList);
        console.log("[menuService] 转换统计:", {
          总路由数: statistics.total,
          可见路由: statistics.visible,
          隐藏路由: statistics.hidden,
          iframe路由: statistics.iframe,
          缓存路由: statistics.cached,
        });

        // 验证转换结果
        const validation = RouteConverter.validate(menuList);
        if (!validation.isValid) {
          console.warn("[menuService] 路由转换验证警告:", validation.errors);
        }
        if (validation.warnings.length > 0) {
          validation.warnings.forEach((warning) =>
            console.warn(`[menuService] 转换警告: ${warning}`),
          );
        }

        return { menuList };
      }
    } catch (error) {
      console.error("[menuService] 获取菜单数据失败:", error);
      throw error instanceof Error ? error : new Error("获取菜单失败");
    }
  },

  /**
   * 扩展组件映射
   * @param customMap 自定义组件映射
   */
  extendComponentMap(customMap: Record<string, string>) {
    RouteConverter.extendComponentMap(customMap);
  },

  /**
   * 扩展图标映射
   * @param customMap 自定义图标映射
   */
  extendIconMap(customMap: Record<string, string>) {
    RouteConverter.extendIconMap(customMap);
  },

  /**
   * 扩展标题映射
   * @param customMap 自定义标题映射
   */
  extendTitleMap(customMap: Record<string, string>) {
    RouteConverter.extendTitleMap(customMap);
  },
};
